﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using Entity.IRepository.Project;
using Entity.ProjectEnt;
using System.Reflection;
using System.Text.RegularExpressions;
using ZFine.Code;
using ZFine.Data;
using ZFine.Domain.Entity;

namespace Logic.Repository.Project
{
    public class PathwayRepository : RepositoryBase<PathwayEntity>, IPathwayRepository
    {
        public int UpdateN(PathwayEntity entity)
        {
            dbcontext.Set<PathwayEntity>().Attach(entity);
            PropertyInfo[] props = entity.GetType().GetProperties();
            foreach (PropertyInfo prop in props)
            {
                if (prop.PropertyType.FullName.Contains("Entity"))
                {
                    break;
                }
                if (prop.GetValue(entity, null) != null)
                {
                    if (prop.GetValue(entity, null).ToString() == "&nbsp;")
                        dbcontext.Entry(entity).Property(prop.Name).CurrentValue = null;
                    dbcontext.Entry(entity).Property(prop.Name).IsModified = true;
                }
            }
            return dbcontext.SaveChanges();
        }

        public int FindListthis(string sql)
        {
            return dbcontext.Database.SqlQuery<int>(sql).FirstOrDefault();
        }


        public List<PathwayEntity> FindList(Expression<Func<PathwayEntity, bool>> predicate)
        {
            //return dbcontext.Set<PathwayEntity>().Include(member => member.UserName).Include(theiscour => theiscour.CourseEntityName).Where(predicate).ToList();
            return dbcontext.Set<PathwayEntity>().Where(predicate).ToList();

        }

        /// <summary>
        /// 回退排车
        /// </summary>
        /// <param name="gudaocarlist">要删除的历史库</param>
        /// <param name="retgudaocarlist">要回退的库</param>
        /// <returns></returns>
        public int SubmitRetClearlist(List<HistoryGudaoCarEntity> gudaocarlist, List<GudaoCarEntity> retgudaocarlist,OperationGudaoCarEntity operation)
        {
            dbcontext.Entry<OperationGudaoCarEntity>(operation).State = EntityState.Modified;

            var BelongCarriage = gudaocarlist.FirstOrDefault().BelongCarriage;//保存有效的附加实体
            foreach (var varhistory in gudaocarlist)
            {
                varhistory.State = false;
                varhistory.ClearGudaoOper = operation;
                dbcontext.Entry<HistoryGudaoCarEntity>(varhistory).State = EntityState.Modified;
            }
            foreach (var itemgudao in retgudaocarlist)
            {
                itemgudao.State = true;
                itemgudao.ClearGudaoOper = operation;
                dbcontext.Entry<OperationGudaoCarEntity>(itemgudao.ClearGudaoOper).State = EntityState.Modified;
                dbcontext.Entry(itemgudao).Reference(f => f.ClearGudaoOper).CurrentValue =
                    itemgudao.ClearGudaoOper;
                itemgudao.isAccomplishPaiche = false;
                if (itemgudao.BelongCarriage != null)
                {
                    itemgudao.BelongCarriage = BelongCarriage;
                    itemgudao.BelongCarriage.State = true;
                    dbcontext.Entry<CarriageEntity>(itemgudao.BelongCarriage).State = EntityState.Modified;
                    dbcontext.Entry(itemgudao).Reference(f => f.BelongCarriage).CurrentValue =
                        itemgudao.BelongCarriage;
                }
                dbcontext.Entry<GudaoCarEntity>(itemgudao).State = EntityState.Modified;
            }
            return dbcontext.SaveChanges();
        }

        /// <summary>
        /// 排车操作
        /// </summary>
        /// <param name="gudaocarlist">有效股道实体list</param>
        /// <param name="historygudaocarlist">历史股道实体list</param>
        /// <param name="operation">操作</param>
        /// <returns></returns>
        public int SubmitClearCarinfo(List<GudaoCarEntity> gudaocarlist,
            List<HistoryGudaoCarEntity> historygudaocarlist, OperationGudaoCarEntity operation)
        {
            dbcontext.Entry<OperationGudaoCarEntity>(operation).State = EntityState.Added;
            if (operation.OperationPersion != null)
            {   
                dbcontext.Entry<UserEntity>(operation.OperationPersion).State = EntityState.Unchanged;
                dbcontext.Entry(operation).Reference(f => f.OperationPersion).CurrentValue = operation.OperationPersion;
            }
            dbcontext.SaveChanges();
            dbcontext.Entry<OperationGudaoCarEntity>(operation).State = EntityState.Unchanged;
            foreach (var historyilte in historygudaocarlist)
            {
                if (historyilte.BelongCarriage != null)
                {
                    historyilte.BelongCarriage.State = false;//将车辆实体志为无效
                    dbcontext.Entry<CarriageEntity>(historyilte.BelongCarriage).State = EntityState.Modified;
                    dbcontext.Entry(historyilte).Reference(f => f.BelongCarriage).CurrentValue =
                        historyilte.BelongCarriage;
                }
                if (historyilte.BelongPathway != null)
                {
                    dbcontext.Entry<PathwayEntity>(historyilte.BelongPathway).State = EntityState.Unchanged;
                    dbcontext.Entry(historyilte).Reference(f => f.BelongPathway).CurrentValue =
                        historyilte.BelongPathway;
                }
                if (historyilte.Operation != null)
                {
                    dbcontext.Entry<OperationGudaoCarEntity>(historyilte.Operation).State = EntityState.Unchanged;
                    dbcontext.Entry(historyilte).Reference(f => f.Operation).CurrentValue =
                        historyilte.Operation;
                }
                if (historyilte.PassOper != null)
                {
                    dbcontext.Entry<OperationGudaoCarEntity>(historyilte.PassOper).State = EntityState.Unchanged;
                    dbcontext.Entry(historyilte).Reference(f => f.PassOper).CurrentValue =
                        historyilte.PassOper;
                }
                if (historyilte.QiPiaoOper != null)
                {
                    dbcontext.Entry<OperationGudaoCarEntity>(historyilte.QiPiaoOper).State = EntityState.Unchanged;
                    dbcontext.Entry(historyilte).Reference(f => f.QiPiaoOper).CurrentValue =
                        historyilte.QiPiaoOper;
                }
                if (historyilte.ClearGudaoOper != null)
                {
                    dbcontext.Entry<OperationGudaoCarEntity>(historyilte.ClearGudaoOper).State = EntityState.Unchanged;
                    dbcontext.Entry(historyilte).Reference(f => f.ClearGudaoOper).CurrentValue =
                        historyilte.ClearGudaoOper;
                }
                if (historyilte.WorkPlanOper != null)
                {
                    dbcontext.Entry<OperationGudaoCarEntity>(historyilte.WorkPlanOper).State = EntityState.Unchanged;
                    dbcontext.Entry(historyilte).Reference(f => f.WorkPlanOper).CurrentValue =
                        historyilte.WorkPlanOper;
                }
                dbcontext.Entry<HistoryGudaoCarEntity>(historyilte).State = EntityState.Added;
            }
            foreach (var gudaocar in gudaocarlist)
            {
                gudaocar.ClearGudaoOper = operation;
                dbcontext.Set<GudaoCarEntity>().Attach(gudaocar);
                gudaocar.State = false;
                if (gudaocar.ClearGudaoOper != null)
                {
                    dbcontext.Set<GudaoCarEntity>().Attach(gudaocar).ClearGudaoOper = gudaocar.ClearGudaoOper;
                    dbcontext.Entry<OperationGudaoCarEntity>(gudaocar.ClearGudaoOper).State = EntityState.Unchanged;
                    dbcontext.Entry(gudaocar).Reference(f => f.ClearGudaoOper).CurrentValue =
                        gudaocar.ClearGudaoOper;
                }
                string sql = string.Format("update GudaoCar set ClearGudaoOper_F_Id='{0}' where F_id='{1}'",
                    operation.F_Id, gudaocar.F_Id);
                dbcontext.Database.ExecuteSqlCommand(sql);
                dbcontext.Entry<GudaoCarEntity>(gudaocar).State = EntityState.Modified;
            }

            return dbcontext.SaveChanges();
        }


        public List<PathwayEntity> FindList(Expression<Func<PathwayEntity, bool>> predicate, Pagination pagination)
        {
            bool isAsc = pagination.sord.ToLower() == "asc" ? true : false;
            string[] _order = pagination.sidx.Split(',');
            MethodCallExpression resultExp = null;
            var tempData = dbcontext.Set<PathwayEntity>().Where(predicate);
            foreach (string item in _order)
            {
                string _orderPart = item;
                _orderPart = Regex.Replace(_orderPart, @"\s+", " ");
                string[] _orderArry = _orderPart.Split(' ');
                string _orderField = _orderArry[0];
                bool sort = isAsc;
                if (_orderArry.Length == 2)
                {
                    isAsc = _orderArry[1].ToUpper() == "ASC" ? true : false;
                }
                var parameter = Expression.Parameter(typeof(PathwayEntity), "t");
                var property = typeof(PathwayEntity).GetProperty(_orderField);
                var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                var orderByExp = Expression.Lambda(propertyAccess, parameter);
                resultExp = Expression.Call(typeof(Queryable), isAsc ? "OrderBy" : "OrderByDescending", new Type[] { typeof(PathwayEntity), property.PropertyType }, tempData.Expression, Expression.Quote(orderByExp));
            }
            tempData = tempData.Provider.CreateQuery<PathwayEntity>(resultExp);
            pagination.records = tempData.Count();
            tempData = tempData.Skip<PathwayEntity>(pagination.rows * (pagination.page - 1)).Take<PathwayEntity>(pagination.rows).AsQueryable();
            return tempData.ToList();
        }

    }
}
